from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
import cv2
import numpy as np
from hyperlpr2 import HyperLPR_plate_recognition

app = FastAPI()

@app.post("/recognize_plate/")
async def recognize_plate(file: UploadFile = File(...)):
    """
    车牌识别

    :param file: 车牌图片
    :return: 车牌号码
    """
    # 读取上传的图片文件内容
    contents = await file.read()
    # 转换成 np.array
    nparr = np.frombuffer(contents, np.uint8)
    # 用cv2解码成图片
    image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    if image is None:
        return JSONResponse(status_code=400, content={"error": "无法解码图片"})
    # 将图片从JPG转换为PNG
    success, png_image = cv2.imencode('.png', image)
    if not success:
        return JSONResponse(status_code=500, content={"error": "图片转换PNG失败"})

    # 将 PNG 数据重新解码成 OpenCV 图像
    png_data = np.frombuffer(png_image, np.uint8)
    decoded_image = cv2.imdecode(png_data, cv2.IMREAD_COLOR)


    # 车牌识别
    result = HyperLPR_plate_recognition(decoded_image)
    print(result)
    print(result[0][0])
    plate_no = result[0][0]

    return {"plate_no": plate_no}


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0')